package com.kqb.common.security.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.kqb.api.auth.bo.UserInfoInTokenBO;
import com.kqb.api.auth.feign.TokenFeignClient;
import com.kqb.common.core.utils.AjaxResult;
import com.kqb.common.security.AuthUserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;

/**
 * @author 杉果树皮
 * @date 2025/4/12 14:09
 * @description:
 */
@Component

public class AuthInterceptor implements HandlerInterceptor {


    @Autowired(required = false)
    TokenFeignClient tokenFeignClient;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("Authorization");
        //token 不存在 返回
        if (StrUtil.isBlank(accessToken)) {
            returnMsg(response, AjaxResult.error("Unauthorized"));
            return false;
        }

        //token 存在 验证token
        AjaxResult ajaxResult = tokenFeignClient.checkToken(accessToken);
        int code = (int) ajaxResult.get("code");
        if (code == 0) {
            returnMsg(response, AjaxResult.error(0, (String) ajaxResult.get("msg")));
            return false;
        }
        if (code == 2) {
            returnMsg(response, AjaxResult.error(2, (String) ajaxResult.get("msg")));
            return false;
        }
        if (code == 3) {
            LinkedHashMap<String, Object> data = (LinkedHashMap<String, Object>) ajaxResult.get("data");
            UserInfoInTokenBO userInfoInTokenBO = BeanUtil.toBean(data, UserInfoInTokenBO.class);
            AuthUserContext.set(userInfoInTokenBO);
            return true;
        }
        return true;
    }

    /**
     * 返回给前端json信息
     *
     * @param response
     */
    public void returnMsg(HttpServletResponse response, AjaxResult ajaxResult) {
        try (PrintWriter writer = response.getWriter()) {
            response.setContentType("application/json;charset=UTF-8");
            JSON res = JSONUtil.parse(ajaxResult);
            writer.println(res.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AuthUserContext.clear();
    }
}
